package cn.com.cetccst.dataupload.sync.restriction;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import java.util.ArrayList;
import java.util.List;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.RestrictionStatusEntity;
import cn.com.cetccst.dataupload.tools.WorkerUtil;
import cn.com.cetccst.tools.log.CommonLogger;

public class RestrictionStatusManager {
    private static RestrictionStatusManager instance;
    private List<RestrictionStatusEntity> previousData;
    private RestrictionStatusManager(Context context) {
        previousData = new ArrayList<>();
        LiveData<List<RestrictionStatusEntity>> restrictionStatusList = PolicyRepository.getInstance().loadRestrictionStatus();
        restrictionStatusList.observeForever(entities -> {
            if (entities != null && !entities.isEmpty() && !previousData.equals(entities)) {
                CommonLogger.info("begin to upload restriction data");
                OneTimeWorkRequest workRequest = WorkerUtil.getOneTimeWorkRequest(UploadRestrictionWorker.class, null);
                WorkManager.getInstance(context).enqueueUniqueWork("UploadRestriction", ExistingWorkPolicy.REPLACE, workRequest);
                previousData = entities;
            } else {
                CommonLogger.info("restriction data is not changed");
            }
        });
    }

    public static void initialize(Context context) {
        if (instance == null) {
            instance = new RestrictionStatusManager(context);
        }
    }

    public static RestrictionStatusManager getInstance() {
        return instance;
    }
}
